相信大家都有碰到過這種問題,以讀取檔案方式處理分析檔案
今天舉一個例子,大家都聽過兩隻老虎這首兒歌吧!
def modifySong(songStr) #將標點符號用空自元取代
for ch in songStr:
if ch in ".,?"
songStr = songStr.replace(ch, '')
return songStr
def wordCount(songCount):
global mydict
songList = songCount.split() #將歌曲轉成串列
print("歌曲串列")
print(songList)
mydict = {wd:songList.count(wd) for wd in set(songList)}
fn = "song.txt"
with open(fn) as file_Obj: #開檔
data = file_Obj.read() #讀檔
print("所讀歌曲")
print(data)
mydict = {} #空字典儲存單字計算結果
print("將字母改成小寫及把標點符號用空自元取代")
song = modifySong(data.lower())
print(song)
wordCount(song) #歌曲單字計算
print("result")
print(mydict)